import numpy as np
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
import torch

# Print detail info of the given np_array.
def show_detail(np_array, comment=None):
    print(comment, "shape:", np_array.shape, "dtype:", np_array.dtype, "max:", np.max(np_array), "min:", np.min(np_array))

def tensor2image(tensor):
    '''
    rosneToT
    ToTensor的反函数，将tensor转换为PIL.Image
    注意会产生失真
    :param tensor: torch.Tensor
    :return: PIL.Image
    '''
    if torch.max(tensor) <= 1.:
        tensor = tensor * 255
    if tensor.size(0) == 3:
        tensor = tensor.permute(1, 2, 0)
    else:
        tensor = tensor.squeeze(0)
    image = np.uint8(tensor.cpu().numpy())
    image = Image.fromarray(image)
    return image


def to_categorical(y, num_classes=None):
    """Converts a class vector (integers) to binary class matrix.

    E.g. for use with categorical_crossentropy.

    # Arguments
        y: class vector to be converted into a matrix
            (integers from 0 to num_classes).
        num_classes: total number of classes.

    # Returns
        A binary matrix representation of the input.
    """
    y = np.array(y, dtype='int').ravel()
    if not num_classes:
        num_classes = np.max(y) + 1
    n = y.shape[0]
    categorical = np.zeros((n, num_classes))
    categorical[np.arange(n), y] = 1
    return np.float32(categorical)

